﻿var me = this,
    formData = arguments[1],
    emp = PAI.Global.getAccount().employee,
    vm = this.lookupViewModel(),
    draftId = PAI.Global.getUrlData('draftId');

var phone = emp.ext_jlrTelephone;
var employeeNo = emp.employeeNo;
var email = emp.email;

var controller = this.lookupController();
var destInstId = controller.destInstId;
var procInstId = controller.procInstId;

//复制表单ID
var formDataId = PAI.Global.getUrlData('formDataId');
if (me.analysis.status == 'launch' && !draftId && !formDataId) {
    formData.GeneralInformation = {
        Applicant: emp.lastName + " " + emp.firstName,
        DateTime: Ext.Date.format(new Date(), 'Y-m-d'),
        ExpenseType: '1',
        cdsid: employeeNo,
        email: email,
        mobile: phone,
        SingleSource: 'No',
        companyC: 'JLRC'
    };
}
formData.approverDesc = '';

var activity = "";
//查询流程节点
Ext.PAIRest.request({
    url: 'formActivity/currentProcInst',
    ns: PAI.application.userServerUrl,
    method: "POST",
    async: false,
    data: {
        "destInstId": destInstId || '',
        "procInstId": procInstId || ''
    },
    success: function (data) {
        var empId = PAI.Global.getAccount().employee.id;
        for (var i = 0; data.currentActivitys.length > i; i++) {
            controller.currentActivity = data.currentActivitys[i].activityName; //节点名称
            controller.currentActivityId = data.currentActivitys[i].activityId;
            for (var j = 0; j < data.currentActivitys[i].empList.length; j++) {
                controller.employeeId = data.currentActivitys[i].empList[j].employeeId;
                if (empId == controller.employeeId) {
                    activity = controller.currentActivity; //当前节点名称
                }
            }
        }

    },
    failure: function (jsondata) {
    }
});

formData.companySection = formData.companySection || {};
formData.companySection.activity = activity;

//if (activity.indexOf('Finance') != -1 || activity.indexOf('CFO') != -1) {
//    var company = PAI.Global.getAccount().employee.ext_jlrOrganization;

//    if (company) {
//        ref.datagrid3.store.on('refresh', function (store) {
//            if (!store.isFirstLoadRefresh) {
//                store.isFirstLoadRefresh = true;
//                store.filterBy(function (item) {
//                    return company.indexOf(item.get('Company')) != -1;
//                });
//            }
//        });
//    }
//}

if (me.analysis.status == 'launch' || me.analysis.status == 'resubmit') {
    var code = '';
    var expenseType = formData.GeneralInformation.ExpenseType;
    switch (expenseType) {
        case '1':
        case '2':
            code = '7f9b174e-a940-4a86-b989-5f962e7e1622';
            break;
        case '6':
            code = 'b3ec2d43-ea96-4052-88bd-6f324ace9790';
            break;
        default:
            break;
    }
    ref.SharingPrinciple.store.removeAll();
    ref.SharingPrinciple.store.code = code;
    ref.SharingPrinciple.store.load();
}

me.on('print', function (myDocument, view, jsondata, myWindow) {

    var hiddenField = [];
    var refs = this.lookupController().getReferences();

    for (var name in refs) {
        if (refs[name].hidden) {
            hiddenField.push(name);
        }
    }

    for (var i = 0; i < hiddenField.length; i++) {
        var _el = myDocument.getElementById(hiddenField[i]);
        if (_el) {
            _el.style = 'display:none;';
        }
    }
    //一些换行的需要单独处理.
    Ext.each(['pi1'], function (field) {

        var _width = refs[field].getEl().getStyle('width').replace('px', '') - 40;

        myDocument.getElementById(field).style.width = _width + 'px'
    });
});

//定义全局提示函数
controller.showMsgTips = function (errors) {
    if (!Ext.isArray(errors)) {
        errors = [errors];
    }

    Ext.toast({
        html: Ext.String.format('<b>{0}</b><ol><li>{1}</li></ol>', language(formCommLang('formInvaild')), errors.join('</li><li>').replace('<br>', '')),
        minWidth: 350,
        maxWidth: 400,
        align: 't',
        cls: Ext.baseCSSPrefix + 'toast' + ' pai-form-invaild',
        autoCloseDelay: 5000,
        closeOnMouseDown: true
    });
};

/**
 * 
 * @param {any} pa
 * @param {any} record
 * @param {any} fn 
 */
controller.getBalance = function (pa, record, fn) {
    //时时抓取Balance数据
    var budgetitemId = ref.BudgetItems.getValue();
    var year = new Date().getFullYear();
    var isReCall = false;

    var isInquiryCall = vm.get('NebulogyForm.isInquiryCall');
    //Enquiry之后不需要实时取最新的Balance.读取公司分摊表格上的Balance.
    if (isInquiryCall == 1) {
        //这里可能是采购表格或者公司分摊表格触发.如果是公司分摊表格直接取值就行了.采购的还需要查询下.
        if (record) {
            controller.balance[pa] = record.get('Balance');
            controller.budgetControl[pa] = record.get('budgetControl');
        } else {
            var findRecord = ref.datagrid3.store.findRecord('ProjectActivity', pa);

            controller.balance[pa] = findRecord.get('Balance');
            controller.budgetControl[pa] = findRecord.get('budgetControl');
        }
    } else {
        var paList = vm.get('NebulogyForm.ProjectActivityList');

        var paId = paList.filter((r) => { return r.ProjectActivity == pa })[0].ID;

        Ext.PAIRest.request({
            ns: PAI.application.serviceUrl,
            url: 'jlr-rest/api/budgetFmebugetItem/page',
            method: "POST",
            async: false,
            data: {
                projectactivityId: paId,
                budgetitemId: budgetitemId,
                yearVal: year,
                company: 'JLRC'
            },
            success: function (data) {

                if (Ext.isEmpty(data.budgetFmebugetItemF04RespS01s)) {
                    controller.showMsgTips(pa + ' does not have Balance, Please select other Project Activity');

                    //如果record传了 则表示这是Company Allocation编辑触发.查询不到值就取表单上原有的Balance
                    if (record) {
                        controller.balance[pa] = record.get('Balance');
                        controller.budgetControl[pa] = record.get('budgetControl');
                    }
                    isReCall = true;
                } else {

                    var curr = data.budgetFmebugetItemF04RespS01s[0];
                    if (curr.valid == 'N') {
                        controller.showMsgTips('The current Balance of ' + pa + ' is Invalid, Please select other Project Activity');

                        isReCall = true;
                    } else {
                        controller.balance[pa] = parseFloat(curr.balance.split(',').join(''));
                        controller.budgetControl[pa] = curr.budgetControl;
                    }
                }
            }
        });
    }
    //调用回调函数
    if (fn && isReCall)
        return fn();
};


if (me.analysis.status == 'launch' || me.analysis.status == 'resubmit') {

    //给所有的numberfield 加上 format:'0,000.00'
    //先遍历所有的表单上的控件 在去遍历 grid 上的控件.
    for (var name in ref) {
        if (ref[name].xtype == 'numberfield') {
            ref[name].format = '0,000.00';
        }
    }

    var setFormat = function (grid) {
        var columns = grid.getColumns();

        for (var i = 0; i < columns.length; i++) {
            if (columns[i].xtype == 'numbercolumn') {
                columns[i].editor.format = '0,000.00';
            }
        }
    };

    setFormat(ref.datagrid2);
    setFormat(ref.datagrid3);
    setFormat(ref.datagrid4);
}


Ext.PAIRest.request({
    ns: PAI.application.serviceUrl,
    url: 'jlr-rest/api/getFiscalYearList',
    method: "POST",
    async: false,
    data: {},
    success: function (data) {
        var fiscalYearArr = [];
        var value = '';
        for (var i = 0; i < data.years.length; i++) {
            var cur = data.years[i];

            fiscalYearArr.push({
                label: `${cur.yearVal}-${parseInt(cur.yearVal) + 1}`,
                value: `${cur.yearVal}_${cur.crossYear}`
            });
            if (!value && cur.crossYear == 'N') {
                value = `${cur.yearVal}_${cur.crossYear}`;
            }
        }
        ref.fiscalYear.store.loadData(fiscalYearArr);

        if (!formData.GeneralInformation.fiscalYear) {
            formData.GeneralInformation.fiscalYear = value
        }
    }
});
